package com.jdy.hotel.ui.forget;

import android.annotation.SuppressLint;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.lifecycle.ViewModelProviders;

import com.jdy.hotel.R;
import com.jdy.hotel.check.CheckHelper;
import com.jdy.hotel.net.ResponseData;
import com.jdy.hotel.support.BaseActivity;
import com.jdy.hotel.support.BaseViewModelFactory;
import com.jdy.hotel.support.view.BaseViewItem;
import com.jdy.hotel.support.view.ControlViewPager;
import com.jdy.hotel.utils.ResourcesUtils;
import com.jdy.hotel.utils.StringUtil;

import java.util.Map;


public class ForgetActivity extends BaseActivity {
    private TextView mTextView;
    private View identityVerificationView, userView;
    private AppCompatButton mCodeButton, mSubmitButton;
    private ColorFilter actionColorFilter, silenceColorFilter;
    private String encryptCode;
    private ControlViewPager viewPager;
    private AppCompatEditText userNameEditText;
    private AppCompatImageView submitAction;

    private CountDownTimer countDownTimer = new CountDownTimer(60 * 1000, 1000) {
        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long millisUntilFinished) {
            mCodeButton.setEnabled(false);
            mCodeButton.getBackground().setColorFilter(silenceColorFilter);
            mCodeButton.setBackground(getResources().getDrawable(R.drawable.button_gray_ripple));
            mCodeButton.setText("" + millisUntilFinished / 1000);
        }

        @Override
        public void onFinish() {
            mCodeButton.setEnabled(true);
            mCodeButton.getBackground().setColorFilter(actionColorFilter);
            mCodeButton.setText(getString(R.string.forget_verification_code_again_action));
            mSubmitButton.setEnabled(false);
            mSubmitButton.getBackground().setColorFilter(silenceColorFilter);
        }
    };

    @Override
    protected int getLayoutSource() {
        return R.layout.activity_register;
    }

    @Override
    protected void createView(Bundle savedInstanceState) {
        mTextView = findViewById(R.id.register_view_title);
        submitAction = findViewById(R.id.register_action_upload);
        submitAction.setVisibility(View.INVISIBLE);
        identityVerificationView = View.inflate(this, R.layout.view_identity_verification, null);
        userView = View.inflate(this, R.layout.view_user, null);
        userNameEditText = userView.findViewById(R.id.register_user_name);
        userNameEditText.setGravity(Gravity.CENTER);
        userNameEditText.setEnabled(false);
        loadingProgressBar = findViewById(R.id.register_load_progress);
        mCodeButton = identityVerificationView.findViewById(R.id.forget_verification_code_action);
        mSubmitButton = identityVerificationView.findViewById(R.id.forget_submit_action);
        viewPager = findViewById(R.id.register_view_pager);
        viewPager.setCanScroll(false);
        //初始化ViewPager
        initViewPager(viewPager, new BaseViewItem(identityVerificationView, R.string.forget_change_password), new BaseViewItem(userView, R.string.forget_change_password));
    }

    @Override
    protected void bindModel() {
        ForgetViewModel forgetViewModel = ViewModelProviders.of(this, new BaseViewModelFactory()).get(ForgetViewModel.class);

        CheckHelper helper = CheckHelper.of(forgetViewModel);

        helper.editTake("userName", getString(R.string.prompt_email), identityVerificationView.findViewById(R.id.forget_user_name))
                .editTake("userPhone", getString(R.string.register_user_phone), identityVerificationView.findViewById(R.id.forget_user_phone))
                .notNull().phone();

        setFormObserver(forgetViewModel.getFormData());
        setRequestObserver(forgetViewModel.getRespondData());

        mCodeButton.setOnClickListener(v -> {
            loadingProgressBar.setVisibility(View.VISIBLE);
            forgetViewModel.getAuthenticationCode();
        });

        mSubmitButton.setOnClickListener(v -> {
            AppCompatEditText editText = identityVerificationView.findViewById(R.id.forget_verification_code);
            if (TextUtils.isEmpty(editText.getText())) {
                editText.setError("请输入验证码！");
                return;
            }

            if (StringUtil.doBCryptMatchs(editText.getText(), encryptCode)) {
                viewPager.setCurrentItem(1);//TODO 这个需要注意ViewPager的View位置
                submitAction.setVisibility(View.VISIBLE);
                if (!forgetViewModel.get().containsKey("Password")) {
                    helper.edit("Password", getString(R.string.prompt_password), userView.findViewById(R.id.register_user_password)).notNull()
                            .equal(getString(R.string.prompt_confirm_password), userView.findViewById(R.id.register_user_confirm_password));
                }
                return;
            }
            showMessage("验证码错误！");
        });

        submitAction.setOnClickListener(v -> {
            loadingProgressBar.setVisibility(View.VISIBLE);
            forgetViewModel.changePassword();
        });
    }

    @Override
    protected void onRespond(ResponseData response) {
        if (response.getCode() == 300) {
            countDownTimer.start();
            mSubmitButton.setEnabled(true);
            mSubmitButton.getBackground().setColorFilter(actionColorFilter);
            Object data = response.getData();
            if (data instanceof String) {
                encryptCode = (String) data;
            }

            if (data instanceof Map) {
                Map mapData = (Map) data;
                encryptCode = (String) mapData.get("Code");
                userNameEditText.setText((CharSequence) mapData.get("UserName"));
            }
        } else if (response.getCode() == 200) {
            showMessage("修改密码成功！");
            finish();
        }

    }

    @Override
    protected void setListeners() {
        findViewById(R.id.register_action_back).setOnClickListener(v -> this.finish());
    }

    @Override
    protected void bindData(Bundle savedInstanceState) {
        mTextView.setText(getString(R.string.forget_change_password));
        silenceColorFilter = new PorterDuffColorFilter(ResourcesUtils.getColor(R.color.gray), PorterDuff.Mode.DARKEN);
        actionColorFilter = new PorterDuffColorFilter(ResourcesUtils.getColor(R.color.button_color), PorterDuff.Mode.DARKEN);
        mSubmitButton.getBackground().setColorFilter(silenceColorFilter);
        mSubmitButton.setEnabled(false);
        mCodeButton.getBackground().setColorFilter(actionColorFilter);
    }
}
